import { PinYin } from './code'

/** 判断是否是数组 */
const isArray = (val) => Array.isArray(val)

//
const unicode = (words, type, flag) => {
  const length = words.length
  let result = []
  for (let i = 0; i < length; i++) {
    const ch = words.substr(i, 1)
    const unicode = ch.charCodeAt(0)
    if (unicode > 40869 || unicode < 19968) {
      result = assemble(ch, result, type)
      continue
    }

    result = assemble(convert(unicode), result, type)
  }

  if (flag) {
    return result
  }

  return result[0]
}

// 拼接返回结果
const assemble = (newly, origin = [], type = 'full') => {
  const result = []

  if (isArray(newly) && newly.length === 0) return origin

  if (origin.length === 0) {
    if (!isArray(newly)) {
      return new Array(newly)
    }

    for (let i = 0; i < newly.length; i++) {
      result.push(convertChars(newly[i], type))
    }
    return result
  }

  for (let i = 0; i < origin.length; i++) {
    if (!isArray(newly)) {
      result.push(origin[i] + newly)
      continue
    }

    for (let k = 0; k < newly.length; k++) {
      result.push(origin[i] + convertChars(newly[k], type))
    }
  }

  return result
}

// 转换返回值
const convertChars = (words, type) => {
  if (type === 'full') {
    return capitalize(words)
  }
  return camel(words)
}

const camel = (words) => {
  if (!words || words.length === 0) {
    return ''
  }
  return words.substr(0, 1).toUpperCase()
}

// 切换首字符大写
const capitalize = (words) => {
  if (!words || words.length === 0) {
    return ''
  }
  const initial = words.substr(0, 1).toUpperCase()
  const spare = words.substr(1, words.length - 2)
  return initial + spare
}

// 将 ASCII 编码转换为拼音
const convert = (unicode) => {
  const spellCh = PinYin[unicode]
  if (!spellCh) {
    return []
  }

  return spellCh
}

export default {
  unicode
}
